package com.atguigu.ting.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.ting.realtime.app.BaseApp;
import com.atguigu.ting.realtime.bean.UserPlayBean;
import com.atguigu.ting.realtime.common.Constant;
import com.atguigu.ting.realtime.funtion.DimAsyncFunction;
import com.atguigu.ting.realtime.util.AtguiguUtil;
import com.atguigu.ting.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/4/14 12:49
 */
public class DwsUserPlayWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsUserPlayWindow().init(
            40011,
            2,
            "DwsUserPlayWindow",
            Constant.TOPIC_DWD_TRAFFIC_PLAY
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        SingleOutputStreamOperator<UserPlayBean> beanStreamWithoutDims = stream
            .process(new ProcessFunction<String, UserPlayBean>() {
                @Override
                public void processElement(String value,
                                           Context ctx,
                                           Collector<UserPlayBean> out) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    
                    Long startTs = obj.getLong("start_ts");
                    Long endTs = obj.getLong("end_ts");
                    
                    Long playDuring = endTs - startTs;
                    
                    if (endTs - startTs > 0) {  // 只保留播放时长大于 0 的数据
                        out.collect(UserPlayBean.builder()
                                        .userId(obj.getString("user_id"))
                                        .albumId(obj.getString("album_id"))
                                        .playDuring(playDuring)  // 该用户对该专辑的播放时长
                                        .ts(endTs)
                                        .build());
                    }
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserPlayBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            // 统计每用户每专辑的播放时长
            .keyBy(bean -> bean.getUserId() + "_" + bean.getAlbumId())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<UserPlayBean>() {
                    @Override
                    public UserPlayBean reduce(UserPlayBean value1,
                                               UserPlayBean value2) throws Exception {
                        value1.setPlayDuring(value1.getPlayDuring() + value2.getPlayDuring());
                        
                        return value1;
                    }
                },
                new ProcessWindowFunction<UserPlayBean, UserPlayBean, String, TimeWindow>() {
                    @Override
                    public void process(String key,
                                        Context ctx,
                                        Iterable<UserPlayBean> elements,
                                        Collector<UserPlayBean> out) throws Exception {
                        UserPlayBean bean = elements.iterator().next();
                        
                        bean.setStt(AtguiguUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(AtguiguUtil.tsToDateTime(ctx.window().getEnd()));
    
                        bean.setTs(System.currentTimeMillis());
    
                        out.collect(bean);
                    }
                }
            );
    
        AsyncDataStream.unorderedWait(
                beanStreamWithoutDims,
                new DimAsyncFunction<UserPlayBean>() {
                    @Override
                    public void addDim(UserPlayBean bean,
                                       JSONObject dim) {
                        bean.setUserGender(dim.getString("GENDER") == null ? "unknown": dim.getString("GENDER"));
                        Long bir = AtguiguUtil.dateToTs(dim.getString("BIRTHDAY"));
                        int age = (int) ((System.currentTimeMillis() - bir) / 1000 / 60 / 60 / 24 / 365);
                        bean.setUserAge(age);
                    }
                
                    @Override
                    public String getId(UserPlayBean bean) {
                        return bean.getUserId();
                    }
                
                    @Override
                    public String getTable() {
                        return "dim_user_info";
                    }
                },
                60,
                TimeUnit.SECONDS
            )
            .addSink(FlinkSinkUtil.getClickHouseSink("dws_user_play_window", UserPlayBean.class));
    }
    
}
